package com.lenovo.nova.weather;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import com.lenovo.nova.util.debug.MyOldLog;
import com.lenovo.nova.util.debug.slog;
import com.lenovo.nova.util.parse.JsonToBeanParser;

public class WeatherUtil {

	public void getWeatherData(){
		String areaid = "101010100";
		String type = "forecast5d";
		String date = "201407311528";
//		String appid = "78ddeee79388493a";
		String appid = "78ddee";
		String key = "3JDIUKiatmyRtYhkFk8oMYTvGpI%3D";

		
		StringBuilder urlBuilder = new StringBuilder(WeatherConstant.predictionUrl);
		urlBuilder.append("?");
		urlBuilder.append("areaid="+areaid);
		urlBuilder.append("&");
		urlBuilder.append("type="+type)
		.append("&")
		.append("date="+date)
		.append("&")
		.append("appid="+appid )
		.append("&")
		.append("key=" + key)
		;
		slog.p("getWeatherDateURL " + urlBuilder.toString());
		
		HttpGet get = new HttpGet(urlBuilder.toString());
		HttpParams httprm = createHttpPrm();
		
		HttpClient client = new DefaultHttpClient(httprm);
		
//		System.setProperty("http.proxyHost", "10.99.20.30");
//		System.setProperty("http.proxyPort", "8080");
		try {
			HttpResponse response = client.execute(get);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			slog.p("statusCode is " + statusCode);
			if(statusCode == 200){
				HttpEntity entity = response.getEntity();
				String content = EntityUtils.toString(entity);
				slog.p("content is " + content);
				WeatherEntity weatherBean = new WeatherEntity();
				try {
					JsonToBeanParser.getInstance().fillBeanWithJson(weatherBean, new JSONObject(content));
					System.out.println(weatherBean);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		} catch (ClientProtocolException e) {
			MyOldLog.e("" + e.toString());
		} catch (IOException e) {
			MyOldLog.e("" + e.toString());
		}
		
		
	}

	private HttpParams createHttpPrm() {
		HttpParams httprm = new BasicHttpParams();
		HttpConnectionParams.setSoTimeout(httprm, 120*1000);
		HttpConnectionParams.setConnectionTimeout(httprm, 60*1000);;
		return httprm;
	}
}
